package dbx

import (
	"fmt"

	"gorm.io/gen"
	"gorm.io/gen/field"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

// 生成代码 ,models map[string, schema.Tabler]
func Gen(mysql *gorm.DB, models map[string]schema.Tabler, dataMap map[string]string, modelPath, outPath string, opts ...gen.ModelOpt) {
	config := gen.Config{
		ModelPkgPath:     modelPath,
		OutPath:          outPath,
		FieldWithTypeTag: true, // generate with gorm column type tag
		Mode:             gen.WithDefaultQuery,
	}

	typeMap := make(map[string]func(columnType gorm.ColumnType) (dataType string), len(dataMap))
	for key, v := range dataMap {
		typeMap[key] = func(detailType gorm.ColumnType) (dataType string) {
			fmt.Println("detailType", detailType)

			dataType = v

			return
		}
	}

	generator := gen.NewGenerator(config)
	generator.UseDB(mysql)
	generator.WithDataTypeMap(typeMap) //DB->
	generator.WithJSONTagNameStrategy(func(columnName string) (tagContent string) {
		fmt.Println("WithJSONTagNameStrategy", columnName)
		return columnName + ",omitempty"
	})

	for _, v := range models {
		err := mysql.AutoMigrate(v)
		if err != nil {
			continue
		}

		generator.ApplyInterface(func() {}, generator.GenerateModel(v.TableName(), opts...))
	}

	generator.Execute()
}

// ModelOpt 自定义gorm tag 映射
func ModelOpt(collection map[string]string) []gen.ModelOpt {
	var data []gen.ModelOpt
	for columnName, newType := range collection {
		data = append(data, gen.FieldType(columnName, newType))
		data = append(data, gen.FieldGORMTag(columnName, func(tag field.GormTag) field.GormTag {
			tag.Set("serializer", "json")
			return tag
		}))
	}

	return data
}

// ModelOpt 自定义gorm tag 映射
func ModelOptNoJson(collection map[string]string) []gen.ModelOpt {
	var data []gen.ModelOpt
	for columnName, newType := range collection {
		data = append(data, gen.FieldType(columnName, newType))
		data = append(data, gen.FieldGORMTag(columnName, func(tag field.GormTag) field.GormTag {
			return tag
		}))
	}

	return data
}
